home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java Primer Plus
/
Java Primer Plus (Waite Group Proess)(1996).iso
/
chapter14
/
trouble.java
< prev
next >
Wrap
Text File
|
1995-12-31
|
982b
|
58 lines
/* critical section example */
class trouble extends Thread {
static int p;
static guard theguard = new guard();
int myval;
boolean flag=true;
public trouble(int x) {myval = x;}
public void run() {
while (true)
messp2();
}
/* just add 2 */
synchronized private void messp() {
p = myval;
p = p + 2;
System.out.print(p);
}
/* add two, protected by a guard */
private void messp2() {
int pvar;
synchronized (theguard) {
p = myval;
p = p + 2;
theguard.c = pvar = p;
}
System.out.print(pvar);
}
}
/* guard class */
class guard {
public int c;
}
/* runner class */
class runtrouble {
public static void main (String args[]) {
trouble A = new trouble(5);
trouble B = new trouble(6);
int mypri = A.getPriority();
if (mypri < Thread.MAX_PRIORITY)
A.setPriority(mypri+1);
A.start();
A.suspend();
B.start();
A.resume();
}
}